#include "Dictionary.h"
#include "Common/FileIO.h"
#include "Common/Attribute.h"
#include <sstream>
#include <algorithm>
#include <map>
#include <iostream>

using namespace std;

string CDictionary::DELIM = " ~`!@#$%^&*()-_+={}[]|\:;',.<>?/\r\n\t";

CDictionary::CDictionary()
{

}

CDictionary::~CDictionary()
{

}

bool CDictionary::Create(bool bStopword)
{
	CFileIO						file;
	char						szBuffer[1024];

	// read stopwords
	if(bStopword)
	{
		file.Create("stopword.txt");
		while(file.ReadLine(szBuffer))
		{
			CAttribute		attr(szBuffer, DELIM);
			vector<string>	list = attr.List();
			
			if(list.size() > 0)
				m_stopword[list[0]] = 1;
		}
		file.Destroy();
	}

	m_bStopword = bStopword;

	return true;
}

void CDictionary::AddSentence(string sentence)
{
	//transform(sentence.begin(), sentence.end(), sentence.begin(), tolower);

	CAttribute		attr(sentence, DELIM);
	vector<string>	list = attr.List();

	for(int i = 0; i < list.size(); i++)
	{
		if(m_bStopword)
		{
			int value = m_stopword[list[i]];
			if(value != 1)
			{
				pair<int, int> value = m_dictionary[list[i]];
				value.second++;
				m_dictionary[list[i]] = make_pair(m_dictionary.size() + 1, value.second);
			}
		}
		else
		{
			pair<int, int>	value  = m_dictionary[list[i]];
			int				nIndex = value.second > 0 ? value.first : m_dictionary.size();
			value.second++;
			m_dictionary[list[i]] = make_pair(nIndex, value.second);
		}
	}
	//cout << m_dictionary.size() << endl;
}

string CDictionary::Query(string sentence)
{
	//transform(sentence.begin(), sentence.end(), sentence.begin(), tolower);

	pair<int, int>	value;
	CAttribute		attr(sentence, DELIM);
	vector<string>	list = attr.List();
	string			str;
	map<int, int>	temp;
	vector<int>		result;

	for(int i = 0; i < list.size(); i++)
	{
		value = m_dictionary[list[i]];

		if(value.first > 0)
			temp[value.first] = value.first;
	}

	for(auto itr = temp.begin(); itr != temp.end(); ++itr)
		result.push_back(itr->second);

	sort(result.begin(), result.end(), [](int a, int b)->bool
	{
		if(a < b) return true;
		return false;
	});

	for(auto itr = result.begin(); itr != result.end(); ++itr)
	{
		stringstream	ss;
		ss << *itr << ":1 "; 
		str += ss.str();
	}
	
	return str;
}

int CDictionary::Index(std::string word)
{
	if(m_dictionary.find(word) == m_dictionary.end())
		return -1;

	pair<int, int> value =m_dictionary[word];

	return value.first;
}

int CDictionary::Frequency(std::string word)
{
	if(m_dictionary.find(word) == m_dictionary.end())
		return 0;

	pair<int, int> value = m_dictionary[word];

	return value.second;
}

int CDictionary::Size()
{
	return m_dictionary.size();
}

